# -*- coding: utf-8 -*-

import requests,json,os,urllib,string,sys
import scrapy
from leisu.sqlHelper import *

reload(sys)
sys.setdefaultencoding('utf8')

class ZqSpider(scrapy.Spider):
    name = 'zq'
    allowed_domains = ['leisu.com']
    handle_httpstatus_list = [301,403,404,500,502]
    offset=20225
    url='https://data.leisu.com/team-'
    endurl=""
    start_urls = [url+str(offset)+endurl]
    def parse(self, response):
        if response.status==404 or response.status==301 or response.status==403 or response.status==500 or response.status==502:
            print self.url+str(self.offset)+'------页面不存在'
        else:
            try:
                ct=response.xpath('/html/body/div[1]/div[2]/div[2]/div[2]/div[3]/div[2]/div/text()[1]').extract()[0]
                cn=ct[0:ct.index("（")-5]
                ct=ct[ct.index("（")+5:]
                en=ct[0:ct.index("，")]
                big=ct[ct.index("：")+1:ct.index("）")]
                url=response.xpath('/html/body/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/@style').extract()[0]
                url="http://"+url[25:len(url)-2]
                print url
                if url[len(url)-4:len(url)-3]==".":
                    self.save_img(url,en)
                    self.save_data(en,cn,big,en+url[len(url)-4:])
                else:
                    self.save_data(en,cn,big,'')
            except Exception,e:
                traceback.print_exc()
                print str(self.offset)+'解析错误！'

        if self.offset < 45615:
            self.offset += 1
            yield scrapy.Request(self.url+str(self.offset)+self.endurl, callback = self.parse,dont_filter=True)

    def save_data(self,en,cn,big,logo):
        print cn+'--'+en+'--'+big+'--'+logo
        if sqlHelper.selectOne("select id from team where cn=%s and typeText=%s",(cn,'足球')):
            if sqlHelper.update("UPDATE team SET source=%s,en=%s WHERE cn=(SELECT cn FROM (SELECT * FROM team WHERE en='' and cn=%s and typeText=%s limit 1) AS t)",(self.url+str(self.offset),en,cn,'足球')):
                print '更新'+cn+'--en>>'+en
            if sqlHelper.update("UPDATE team SET source=%s,big=%s WHERE cn=(SELECT cn FROM (SELECT * FROM team WHERE big='' and cn=%s and typeText=%s limit 1) AS t)",(self.url+str(self.offset),big,cn,'足球')):
                print '更新'+cn+'--big>>'+big
            if sqlHelper.update("UPDATE team SET source=%s,logo=%s WHERE cn=(SELECT cn FROM (SELECT * FROM team WHERE logo='' and cn=%s and typeText=%s limit 1) AS t)",(self.url+str(self.offset),logo,cn,'足球')):
                print '更新'+cn+'--logo>>'+logo
        else:
            sqlHelper.update("insert into team(type,typeText,cn,en,logo,big,source) values(%s,%s,%s,%s,%s,%s,%s)",(30,'足球',cn,en,en,big,self.url+str(self.offset)))
        return True
    
    def save_img(self,img_url,file_name,file_path='zq'):
        try:
            if not os.path.exists(file_path):
                print '文件夹',file_path,'不存在，重新建立'
                #os.mkdir(file_path)
                os.makedirs(file_path)
            #获得图片后缀
            file_suffix = os.path.splitext(img_url)[1]
            #拼接图片名（包含路径）
            filename = '{}{}{}{}'.format(file_path,os.sep,file_name,file_suffix)
#       m下载图片，并保存到文件夹中
            urllib.urlretrieve(img_url,filename=filename)
        except IOError as e:
            print '文件操作失败',e
        except Exception as e:
            print '错误 ：',e

